<?php
namespace app\admin\controller;
use app\admin\model\ShopSpecification;
use \app\admin\model\User;
use \app\admin\controller\BaseController;
use app\admin\model\Order as OrderDb;
use app\admin\model\OrderShop;
use app\admin\model\Shop;
use think\Db;
use think\Collection;

class Order extends BaseController
{
    protected $order;
    public function __construct(OrderDb $order)
    {
        $this->order = $order;
    }
    /**
     * 订单首页
     * @return \think\response\View
     */
    public function index(OrderShop $orderShop)
    {
        $this->isLogin();
        if(request()->isPost()){
            $orders = $this->orderSearch($orderShop);
            if(count($orders) == '0') $this->error('该订单不存在');
        }else{
            //所有订单
            $orders = $this->order->with('orderGoodsInfos.goods')
                ->field('order_number,create_time,order_money,order_staff,order_addr,user_id,buyer_name,order_use,
                pay_number,pay_staff,pay_status,pay_time,buyer_message,freight,user_remind,remind_time,remarks,finish_time,
                close_time,freight_staff,refund_time,refund_finish_time,buyer_phone')
                ->order('create_time desc')
                ->paginate(10);
            $nums = $this->order->getOrderShopNumSum();
            foreach($orders as $key=>$order){
                foreach($nums as $num){
                    if($order['order_number'] == $num['order_number']){
                        $order['shop_num_sum'] = $num['numTotal'];
                    }
                }
            }
        }
        $list = $this->order->numList();
        return view('order/index',compact('list','orders'));
	   }
    public function update(User $user)
    {
        $this->isLogin();
        return view('', compact(''));
    }
    /**
     * 订单备注
     * @return bool|mixed
     */
    public function orderRemarks()
    {
        $this->isLogin();
        if(!input('param.remarks') && !input('param.order_num')) {
            return $this>setError('参数不能为空');
        }
        $post['remarks'] = input('post.remarks');
        $result = $this->order->where(['order_number' => input('post.order_num')])->update($post);
        if(!$result) {
            return $this->setError('添加备注失败');
        }
        return $this->setSuccess('添加备注成功');
    }
    //订单首页买家提醒订单
    public function remindOrders(OrderShop $orderShop)
    {
        $this->isLogin();
        if(request()->isPost()){
            $remindOrders = $this->remindSearch($orderShop);
            if(count($remindOrders) == '0') $this->error('用户提醒订单中不存在该订单');
        }else{
            $remindOrders = $this->getRemindOrder();     //买家提醒订单
            $nums = $this->order->getOrderShopNumSum();
            foreach($remindOrders as $key=>$order){
                foreach($nums as $num){
                    if($order['order_number'] == $num['order_number']){
                        $order['shop_num_sum'] = $num['numTotal'];
                    }
                }
            }
        }
        $list = $this->order->numList();
        return view('order/remindOrder',compact('list','remindOrders'));
    }
    //订单首页退款/售后订单
    public function refundOrders(OrderShop $orderShop)
    {
        $this->isLogin();
        if(request()->isPost()){
            $refundOrders = $this->refundSearch($orderShop);
            if(count($refundOrders) == '0') $this->error('退款、退货订单中不存在该订单');
        }else{
            $refundOrders = $this->getRefundOrder();    //退款/售后订单
            $nums = $this->order->getOrderShopNumSum();
            foreach($refundOrders as $key=>$order){
                foreach($nums as $num){
                    if($order['order_number'] == $num['order_number']){
                        $order['shop_num_sum'] = $num['numTotal'];
                    }
                }
            }
        }
        $list = $this->order->numList();
        return view('order/refundOrder', compact('list','refundOrders'));
    }
    //订单首页待支付订单
    public function pendingPayOrders(OrderShop $orderShop)
    {
        $this->isLogin();
        if(request()->isPost()){
            $pendingPayOrders = $this->pendingPaySearch($orderShop);
            if(count($pendingPayOrders) == '0') $this->error('待支付订单中不存在该订单');
        }else{
            $pendingPayOrders = $this->getPendingPayOrder();//待支付订单
            $nums = $this->order->getOrderShopNumSum();
            foreach($pendingPayOrders as $key=>$order){
                foreach($nums as $num){
                    if($order['order_number'] == $num['order_number']){
                        $order['shop_num_sum'] = $num['numTotal'];
                    }
                }
            }
        }
        $list = $this->order->numList();
        return view('order/pendingPayOrder', compact('list','pendingPayOrders'));
    }
    //订单首页待发货订单
    public function pendingSendOrders(OrderShop $orderShop)
    {
        $this->isLogin();
        if(request()->isPost()){
            $pendingSendOrders = $this->pendingSendSearch($orderShop);
            if(count($pendingSendOrders) == '0') $this->error('待发货订单中不存在该订单');
        }else{
            $pendingSendOrders = $this->getPendingSendOrder();//待发货订单
            $nums = $this->order->getOrderShopNumSum();
            foreach($pendingSendOrders as $key=>$order){
                foreach($nums as $num){
                    if($order['order_number'] == $num['order_number']){
                        $order['shop_num_sum'] = $num['numTotal'];
                    }
                }
            }
        }
        $list = $this->order->numList();
        return view('order/pendingSendOrder', compact('list','pendingSendOrders'));
    }
    //订单首页上架商品订单
//    public function groundingShopOrders(OrderShop $orderShop)
//    {
//        $this->isLogin();
//        if(request()->isPost()){
//            $groundingShopOrders = $this->groundingShop($orderShop);
//            if(count($groundingShopOrders) == 0){
//                return $this->error('上架商品订单中不存在该订单');
//            }
//        }else{
//            $groundingShopOrders = $this->orderShopIsUse(); //上架商品订单
//        }
//        $list = $this->order->numList();
//        return view('order/groundingShopOrder', compact('list','groundingShopOrders'));
//    }
    //订单首页异常订单
    public function abnormalOrders(OrderShop $orderShop)
    {
        $this->isLogin();
        if(request()->isPost()){
            $abnormalOrders = $this->abnormalSearch($orderShop);
            if(count($abnormalOrders) == '0') $this->error('异常订单中不存在该订单');
        }else{
            $abnormalOrders = $this->getAbnormalOrder();//异常订单
            $nums = $this->order->getOrderShopNumSum();
            foreach($abnormalOrders as $key=>$order){
                foreach($nums as $num){
                    if($order['order_number'] == $num['order_number']){
                        $order['shop_num_sum'] = $num['numTotal'];
                    }
                }
            }
        }
        $list = $this->order->numList();
        return view('order/abnormalOrder', compact('list','abnormalOrders'));
    }
    //订单首页交易完成订单
    public function finishOrders(OrderShop $orderShop)
    {
        $this->isLogin();
        if(request()->isPost()){
            $finishOrders = $this->finishSearch($orderShop);
            if(count($finishOrders) == '0') $this->error('交易完成订单中不存在该订单');
        }else{
            $finishOrders = $this->getFinishOrder();//交易完成订单
            $nums = $this->order->getOrderShopNumSum();
            foreach($finishOrders as $key=>$order){
                foreach($nums as $num){
                    if($order['order_number'] == $num['order_number']){
                        $order['shop_num_sum'] = $num['numTotal'];
                    }
                }
            }
        }
        $list = $this->order->numList();
        return view('order/finishOrder', compact('list','finishOrders'));
    }
    //订单首页交易关闭订单
    public function closeOrders(OrderShop $orderShop)
    {
        $this->isLogin();
        if(request()->isPost()){
            $closeOrders = $this->closeSearch($orderShop);
            if(count($closeOrders) == 0) $this->error('交易关闭订单中不存在该订单');
        }else{
            $closeOrders =  $this->getCloseOrder();//交易关闭订单
            $nums = $this->order->getOrderShopNumSum();
            foreach($closeOrders as $key=>$order){
                foreach($nums as $num){
                    if($order['order_number'] == $num['order_number']){
                        $order['shop_num_sum'] = $num['numTotal'];
                    }
                }
            }
        }
        $list = $this->order->numList();
        return view('order/closeOrder', compact('list','closeOrders'));
    }
    /**
     * 操作订单
     * @param OrderShop $orderShop
     * @return \think\response\View
     */
    public function queryOrder()
    {
        $this->isLogin();
        $orders = $this->order->where('order_number',input('order_number'))
            ->field('id,order_number,create_time,order_money,order_staff,order_addr,user_id,buyer_name,order_use,
                pay_number,pay_staff,pay_status,pay_time,buyer_message,freight,user_remind,remind_time,remarks,finish_time,
                close_time,freight_staff,refund_time,refund_finish_time,buyer_phone')
            ->select()->toArray();
        $shops = $this->order->getOrderShops(input('order_number'));
        $all = $this->shopCount($shops);
        return view('order/queryOrder', compact('orders','shops','all'));
    }
    //添加物流信息到订单表
    public function logisticsAdd()
    {
        $this->isLogin();
        $data['logistics_num'] = input('logistics_num');
        $data['send_mode'] = input('send_mode');
        $recode = $this->order->where('order_number',input('order_number'))->update($data);
        if(!$recode){
            return json(['code'=>300,'msg'=>'操作失败，请联系客服']);
        }
        $data = [
            'freight_staff'=> 1,
            'shop_send_time'=>time()
        ];
        $result = $this->order->where('order_number',input('order_number'))->update($data);  //确认发货后修改发货状态
        if(!$result) $this->error('商品发货状态编辑失败');
        return json(['code'=>200,'msg'=>'发货成功']);
    }
    /**
     * 确认发货并减少库存
     */
//    public function sendGoods( $orderShop)
//    {
//        $this->isLogin();
//        $data = [
//            'freight_staff'=> 1,
//            'shop_send_time'=>time()
//        ];
//        Db::startTrans();
//        try{
//        $result = $this->order->where('order_number',input('order_number'))->update($data);  //确认发货后修改发货状态
//        if(!$result){
//            throw new \Exception('商品发货状态编辑失败');
//        }
//        $sendOrders = $orderShop->where('order_number',input('order_number'))->field('shop_id,shop_num,member_id,spec_id')->select()->toArray();
//        foreach($sendOrders as $val){
//            $num = intval($val['shop_num']);
//            $shop = new Shop();
//            $res = $shop->where('id',$val['shop_id'])->where('member_id',$val['member_id'])->setDec('stock_num',$num);
//            if(!$res){
//                throw new \Exception('商品总库存编辑失败');
//            }
//            $shopSpecification = new ShopSpecification();
//            $recode = $shopSpecification->where('id',$val['spec_id'])->setDec('stock_num',$num);
//            if(!$recode){
//                throw new \Exception('商品规格库存编辑失败');
//            }
//        }
//        Db::commit();
//        }catch(\Exception $e){
//            // 回滚事务
//            Db::rollback();
//            return json(['code'=> 300,'msg'=>$e->getmessage()]);
//        }
//        return json(['code'=>200,'msg'=>'发货成功']);
//    }
    /**
     * 订单详情
     * @param OrderShop $orderShop
     * @return \think\response\View
     */
    public function orderDetail()
    {
        $this->isLogin();
        $orders = $this->order->where('order_number',input('order_number'))->select()->toArray();
        $shops = $this->order->getOrderShops(input('order_number'));
        $all = $this->shopCount($shops);
        return view('order/orderDetail', compact('orders','shops','all'));
    }
    //订单（操作、详情里）的无效订单处理
//    public function orderInvalid()
//    {
////        dump(input('order_number'));
//    }
    /**
     * 删除订单
     */
    public function orderDelete()
    {
        $this->isLogin();
        $result = $this->order->where('order_number',input('order_number'))->update(['order_use'=>2]);
        if(!$result){
            return $this->error(' 订单删除失败');
        }
        return $this->success('订单删除成功','admin/order/index');
   }
   //待发货订单修改收货人手机号和收货人地址
    public function orderAddrUpdate()
    {
       $this->isLogin();
       if(request()->isPost()){
           $data = [
               'order_addr'=>input('newAddress'),
               'buyer_phone'=>input('newphonenum')
           ];
           $result = $this->order->where('order_number',input('order_num'))->update($data);
           if(!$result){
               return json(['code'=>100,'msg'=>'修改失败']);
           }
           return json(['code'=>200,'msg'=>'修改成功']);
       }
    }
    /**
     * 计算商品总价格和运费总价格
     * @param $shops
     * @return mixed
     */
    public function shopCount($shops)
    {
        $this->isLogin();
        $goods_total = 0;
        $goods_num = 0;
        foreach($shops as $shop){
            $goods_total += intval($shop['shop_total']);
            $goods_num += intval($shop['shop_num']);
        }
        $all['goods_total'] = $goods_total; //订单商品的总金额
        $all['goods_num'] = $goods_num;     //订单商品的总数量
        return $all;
    }
    //订单搜索(根据商品名搜索订单）
    public function orderSearch($orderShop)
    {
        $this->isLogin();
        $order_number = input('search');
        $order = $this->order->where('order_number',$order_number)
            ->field('id,order_number,create_time,order_money,order_staff,order_addr,user_id,buyer_name,order_use,
                pay_number,pay_staff,pay_status,pay_time,buyer_message,freight,user_remind,remind_time,remarks,finish_time,
                close_time,freight_staff,refund_time,refund_finish_time,buyer_phone')
            ->paginate(10);
        $nums = $orderShop->searchShopNumSum($order_number);
        foreach($order as $key=>$or){
            foreach($nums as $num){
                if($or['order_number'] == $num['order_number']){
                    $or['shop_num_sum'] = $num['numTotal'];
                }
            }
        }
        return $order;
    }
    /**
     * 买家提醒订单
     * @return \think\Paginator
     */
    public function getRemindOrder()
    {
        $this->isLogin();
        return $this->order->with('orderGoodsInfos.goods')
            ->where('user_remind',1)
            ->where('order_use','<>',2)
            ->field('order_number,create_time,order_money,order_staff,order_addr,user_id,buyer_name,order_use,
                pay_number,pay_staff,pay_status,pay_time,buyer_message,freight,user_remind,remind_time,remarks,finish_time,
                close_time,freight_staff,refund_time,refund_finish_time,buyer_phone')
            ->order('create_time desc')
            ->paginate(10); //用户提醒订单
    }
    /**
     * 获取搜索订单商品的shop_num和
     * @param $orderShop
     * @return \think\Paginator
     */
    public function remindSearch($orderShop)
    {
        $this->isLogin();
        $order_number = input('search');
        $order = $this->order->where('order_number',$order_number)->where('user_remind',1)->paginate(10);
        $nums = $orderShop->searchShopNumSum($order_number);
        foreach($order as $key=>$or) {
            foreach ($nums as $num) {
                if ($or['order_number'] == $num['order_number']) {
                    $or['shop_num_sum'] = $num['numTotal'];
                }
            }
        }
        return $order;
    }
    /**
     * 退款/售后订单
     * @return \think\Paginator
     */
    public function getRefundOrder()
    {
        $this->isLogin();
        return $this->order->with('orderGoodsInfos.goods')
            ->where('order_staff',5)
            ->whereOr('order_staff',6)
            ->where('order_use','<>',2)
            ->field('order_number,create_time,order_money,order_staff,order_addr,user_id,buyer_name,order_use,
                pay_number,pay_staff,pay_status,pay_time,buyer_message,freight,user_remind,remind_time,remarks,finish_time,
                close_time,freight_staff,refund_time,refund_finish_time,buyer_phone')
            ->order('create_time desc')
            ->paginate(10);
    }
    /**
     * 搜索订单商品的shop_num和
     * @param $orderShop
     * @return \think\Paginator
     */
    public function refundSearch($orderShop)
    {
        $this->isLogin();
        $order_number = input('search');
        $order = $this->order->where('order_number',$order_number)->where('order_staff',5)->whereOr('order_staff',6)->paginate(10);
        $nums = $orderShop->searchShopNumSum($order_number);
        foreach($order as $key=>$or) {
            foreach ($nums as $num) {
                if ($or['order_number'] == $num['order_number']) {
                    $or['shop_num_sum'] = $num['numTotal'];
                }
            }
        }
        return $order;
    }
    /**
     * 待支付订单
     * @return \think\Paginator
     */
    public function getPendingPayOrder()
    {
        $this->isLogin();
        return $this->order->with('orderGoodsInfos.goods')
            ->where('order_staff',1)
            ->where('order_use','<>',2)
            ->order('create_time desc')
            ->paginate(10);
    }
    public function pendingPaySearch($orderShop){
        $this->isLogin();
        $order_number = input('search');
        $order = $this->order->where('order_number',$order_number)->where('order_staff',1)->paginate(10);
        $nums = $orderShop->searchShopNumSum($order_number);
        foreach($order as $key=>$or) {
            foreach ($nums as $num) {
                if ($or['order_number'] == $num['order_number']) {
                    $or['shop_num_sum'] = $num['numTotal'];
                }
            }
        }
        return $order;
    }
    /**
     *  待发货订单
     * @return \think\Paginator
     */
    public function getPendingSendOrder()
    {
        $this->isLogin();
        return $this->order->with('orderGoodsInfos.goods')
            ->where('order_staff',2)
            ->where('freight_staff',0)
            ->where('order_use','<>',2)
            ->field('order_number,create_time,order_money,order_staff,order_addr,user_id,buyer_name,order_use,
                pay_number,pay_staff,pay_status,pay_time,buyer_message,freight,user_remind,remind_time,remarks,finish_time,
                close_time,freight_staff,refund_time,refund_finish_time,buyer_phone')
            ->order('create_time desc')
            ->paginate(10);
    }
    public function pendingSendSearch($orderShop)
    {
        $this->isLogin();
        $order_number = input('search');
        $order = $this->order->where('order_number',$order_number)->where('order_staff',2)->where('freight_staff',0)->paginate(10);
        $nums = $orderShop->searchShopNumSum($order_number);
        foreach($order as $key=>$or) {
            foreach ($nums as $num) {
                if ($or['order_number'] == $num['order_number']) {
                    $or['shop_num_sum'] = $num['numTotal'];
                }
            }
        }
        return $order;
    }
    /**
     * 用户已删除订单
     * @return \think\Paginator
     */
    public function getAbnormalOrder()
    {
        $this->isLogin();
        return $this->order->with('orderGoodsInfos.goods')
            ->where('order_use',2)
            ->field('order_number,create_time,order_money,order_staff,order_addr,user_id,buyer_name,order_use,
                pay_number,pay_staff,pay_status,pay_time,buyer_message,freight,user_remind,remind_time,remarks,finish_time,
                close_time,freight_staff,refund_time,refund_finish_time,buyer_phone')
            ->order('create_time desc')
            ->paginate(10);
    }
    public function abnormalSearch($orderShop)
    {
        $this->isLogin();
        $order_number = input('search');
        $order = $this->order->where('order_number',$order_number)->where('order_use',1)->paginate(10);
        $nums = $orderShop->searchShopNumSum($order_number);
        foreach($order as $key=>$or) {
            foreach ($nums as $num) {
                if ($or['order_number'] == $num['order_number']) {
                    $or['shop_num_sum'] = $num['numTotal'];
                }
            }
        }
        return $order;
    }
    /**
     * 交易完成订单
     * @return \think\Paginator
     */
    public function getFinishOrder()
    {
        $this->isLogin();
        return $this->order->with('orderGoodsInfos.goods')
            ->where('order_staff',3)
            ->where('order_use','<>',2)
            ->field('order_number,create_time,order_money,order_staff,order_addr,user_id,buyer_name,order_use,
                pay_number,pay_staff,pay_status,pay_time,buyer_message,freight,user_remind,remind_time,remarks,finish_time,
                close_time,freight_staff,refund_time,refund_finish_time,buyer_phone')
            ->order('create_time desc')
            ->paginate(10);
    }
    public function finishSearch($orderShop)
    {
        $this->isLogin();
        $order_number = input('search');
        $order = $this->order->where('order_number',$order_number)->where('order_staff',3)->paginate(10);
        $nums = $orderShop->searchShopNumSum($order_number);
        foreach($order as $key=>$or) {
            foreach ($nums as $num) {
                if ($or['order_number'] == $num['order_number']) {
                    $or['shop_num_sum'] = $num['numTotal'];
                }
            }
        }
        return $order;
    }
    /**
     * 交易关闭订单
     * @return \think\Paginator
     */
    public function getCloseOrder()
    {
        $this->isLogin();
        return $this->order->with('orderGoodsInfos.goods')
            ->where('order_staff',4)
            ->where('order_use','=',1)
            ->field('order_number,create_time,order_money,order_staff,order_addr,user_id,buyer_name,order_use,
                pay_number,pay_staff,pay_status,pay_time,buyer_message,freight,user_remind,remind_time,remarks,finish_time,
                close_time,freight_staff,refund_time,refund_finish_time,buyer_phone')
            ->order('create_time desc')
            ->paginate(10);
    }
    public function closeSearch($orderShop)
    {
        $this->isLogin();
        $order_number = input('search');
        $order = $this->order->where('order_number',$order_number)->where('order_staff',4)->paginate(10);
        $nums = $orderShop->searchShopNumSum($order_number);
        foreach($order as $key=>$or) {
            foreach ($nums as $num) {
                if ($or['order_number'] == $num['order_number']) {
                    $or['shop_num_sum'] = $num['numTotal'];
                }
            }
        }
        return $order;
    }
    /**
     * 上架商品订单
     * @return static
     */
//    public function orderShopIsUse()
//    {
//        $this->isLogin();
//        $order=$this->order
//            ->field('id,order_number,create_time,order_money,order_staff,order_addr,user_id,buyer_name,order_use,
//                pay_number,pay_staff,pay_status,pay_time,buyer_message,freight,user_remind,remind_time,remarks,finish_time,
//                close_time,freight_staff,refund_time,refund_finish_time,buyer_phone')
//            ->select()->filter(function($it)
//        {
//            $result=$it->goods;//有不为0的则忽略该订单
//            foreach ($result as $key => $value){
//              if($value->is_use=='0'){
//                  return true;
//              };
//              return false;
//            }
//        });
//      return $order;
//    }
//    public function groundingShop($orderShop)
//    {
//        $this->isLogin();
//        $order_number = input('search');
//        $order = $this->orderShopIsUse();
//        $nums = $orderShop->searchShopNumSum($order_number);
//        foreach($order as $key=>$or) {
//            foreach ($nums as $num) {
//                if ($or['order_number'] == $num['order_number']) {
//                    $or['shop_num_sum'] = $num['numTotal'];
//                }
//            }
//        }
//        return $order;
//    }

}